<template>
    <div class="app-container">
        <el-form  :inline="true" v-show="showSearch" label-width="168px">
            <el-form-item label="tableNameIsNotNull" >
                <el-input v-model="queryParams.autumnParams.tableNameIsNotNull"
                          @keyup.enter.native="handleQuery"
                >
                </el-input>
            </el-form-item>
            <el-form-item label="tableNameIsNotEmpty" >
                <el-input v-model="queryParams.autumnParams.tableNameIsNotEmpty"
                          @keyup.enter.native="handleQuery"
                >
                </el-input>
            </el-form-item>
            <el-form-item label="tableNameIsEmpty" >
                <SksCheckbox
                    @change="handleQuery()"
                    :formData="queryParams.autumnParams"
                    propName="tableNameIsEmpty">
                </SksCheckbox>
            </el-form-item>
            <el-form-item label="tableNameLike" >
                <el-input v-model="queryParams.autumnParams.tableNameLike"
                          @keyup.enter.native="handleQuery"
                >
                </el-input>
            </el-form-item>


            <el-form-item label="tableName" >
                <el-input v-model="queryParams.autumnParams.tableName"
                          @keyup.enter.native="handleQuery"
                >
                </el-input>
            </el-form-item>


            <el-form-item label="tableNameNot" >
                <el-input v-model="queryParams.autumnParams.tableNameNot"
                          @keyup.enter.native="handleQuery"
                >
                </el-input>
            </el-form-item>

            <el-form-item label="tableNameIn" >
                <AutumnFilterParamSelectMultiple v-model="queryParams.autumnParams.tableNameIn"
                                                 :clearable="true"
                                                 @input="handleQuery"
                                                 :optionList="tableNameOptions"
                >

                </AutumnFilterParamSelectMultiple>
            </el-form-item>

            <el-form-item label="tableNameNotIn" >
                <AutumnFilterParamSelectMultiple v-model="queryParams.autumnParams.tableNameNotIn"
                                                 :clearable="true"
                                                  @input="handleQuery"
                                                 :optionList="tableNameOptions"
                >

                </AutumnFilterParamSelectMultiple>
            </el-form-item>

            <el-form-item label="updateTimeBetween" >
                <AutumnFilterParamDateRange v-model="queryParams.autumnParams.updateTimeBetween"
                                                 :clearable="true"
                                                 @input="handleQuery"
                >

                </AutumnFilterParamDateRange>
            </el-form-item>
        </el-form>

        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">



            <el-form-item label="表名称" prop="tableName">
                <el-input
                    v-model="queryParams.tableName"
                    placeholder="请输入表名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="表描述" prop="tableComment">
                <el-input
                    v-model="queryParams.tableComment"
                    placeholder="请输入表描述"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                    v-model="dateRange"
                    size="small"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    type="daterange"
                    range-separator="-"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-download"
                    size="mini"
                    @click="handleGenTable"
                >生成</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="info"
                    icon="el-icon-upload"
                    size="mini"
                    @click="openImportTable"
                >导入</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleEditTable"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                >删除</el-button>
            </el-col>
            <el-button
                type="info"
                size="mini"
                icon="el-icon-picture-outline-round"
                @click="initTableBuild"
            >初始化table</el-button>
            <el-button
                type="success"
                size="mini"
                icon="el-icon-star-off"
                @click="dialogVisible = true"
            >建表SQL格式化</el-button>

            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" type="index" width="50" align="center">
                <template slot-scope="scope">
                    <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="表名称"
                align="center"
                prop="tableName"
                :show-overflow-tooltip="true"
                width="130"
            />
            <el-table-column
                label="表描述"
                align="center"
                prop="tableComment"
                :show-overflow-tooltip="true"
                width="130"
            />
            <el-table-column
                label="实体"
                align="center"
                prop="className"
                :show-overflow-tooltip="true"
                width="130"
            />
            <el-table-column label="创建时间" align="center" prop="createTime" width="160" />
            <el-table-column label="更新时间" align="center" prop="updateTime" width="160" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-view"
                        @click="handlePreview(scope.row)"
                    >预览</el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-edit"
                        @click="handleEditTable(scope.row)"
                    >编辑</el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                    >删除</el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-refresh"
                        @click="handleSynchDb(scope.row)"
                    >同步</el-button>
                    <el-button
                        type="text"
                        size="small"
                        icon="el-icon-download"
                        @click="handleGenTable(scope.row)"
                    >生成代码</el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
        <!-- 生成SQL语句的弹框 -->
        <el-dialog  :close-on-click-modal="false"  title="输入SQL语句" :visible.sync="dialogVisible" width="60%" >
            <el-input type="textarea" :rows="10"   placeholder="请输入内容" v-model="textarea"></el-input>
            <el-button class="btn" type="primary" @click="handleSqlToInitTableInfo">转换</el-button>
            <!--        class="sql11"-->
            <el-input :rows="10"  readonly type="textarea"  v-model="sql"></el-input>
            <span slot="footer" class="dialog-footer">
        <el-button  type="primary" @click="close">关闭</el-button>
      </span>
        </el-dialog>
        <!-- 预览界面 -->
        <el-dialog  :close-on-click-modal="false"  :title="preview.title" :visible.sync="preview.open" width="80%" top="5vh" append-to-body>
<!--            <el-tabs v-model="queryParamsTabPaneFilterValue" type="card" @tab-click="handleChangeQueryParamsTabPane()">-->
<!--                <template v-for="(item, index) in tabPaneFilterOptionList" >-->
<!--                    <el-tab-pane-->
<!--                        :disabled="loading"-->
<!--                        :label="item.dictLabel"-->
<!--                        :name="''+item.dictValue">-->
<!--                    </el-tab-pane>-->
<!--                </template>-->
<!--            </el-tabs>-->
            <el-radio-group v-model="queryParamsTabPaneFilterValue" size="small" @input="handleChangeQueryParamsTabPane()">
                <template v-for="(item, index) in tabPaneFilterOptionList" >
                    <el-radio-button
                        :label="''+item.dictValue">{{item.dictLabel}}</el-radio-button>
                </template>
            </el-radio-group>


            <el-tabs v-if="queryParamsTabPaneFilterValue==1" v-model="preview.activeName">
                <el-tab-pane
                    :disabled="preview.loading"
                    v-for="(value, key) in preview.data"
                    :label="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
                    :name="key.substring(key.lastIndexOf('/')+1,key.indexOf('.vm'))"
                    :key="key"
                >
                    <el-button size="mini" type="primary" @click="handleClipboard(value,$event)">复制代码</el-button>
                    <pre
                    >{{ value }}</pre>
                </el-tab-pane>
            </el-tabs>
            <el-tabs v-if="queryParamsTabPaneFilterValue==2" v-model="groupPreview.activeName">
                <template
                    v-for="(templateModel,groupName) in groupPreview.data"
                >
                    <el-tab-pane
                        :disabled="groupPreview.loading"
                        :label="groupName"
                        :name="groupName"
                        :key="groupName"
                    >
                        <el-tabs v-model="templateModel.groupActiveName">
                            <el-tab-pane
                                :disabled="groupPreview.loading"
                                v-for="(value, key) in templateModel.templateMap"
                                :label="key"
                                :name="key"
                                :key="key"
                            >
                                <el-button size="mini" type="primary" @click="handleClipboard(value,$event)">复制代码</el-button>
                                <pre
                                >{{ value }}</pre>
                            </el-tab-pane>
                        </el-tabs>
                    </el-tab-pane>
                </template>
            </el-tabs>

        </el-dialog>


        <import-table ref="import" @ok="handleQuery" />

        <init-table ref="initTable" @ok="handleQuery" />
    </div>
</template>

<script>
import {tableBuild, listTable, previewTable, delTable, genCode, synchDb } from "/src/api/tool/gen";
import importTable from "./importTable";
import { downLoadZip } from "/src/utils/zipdownload";
import initTable from "./initTable";
import clipboard from '/src/utils/clipboard'

import request from "../../../utils/request";
// 预览生成的分组代码
export function groupPreviewTable(tableId) {
    return request({
        url: '/tool/gen/groupPreview/' + tableId,
        method: 'get'
    })
}

import ClipboardJS from 'clipboard'

import * as autumnTestScript from './autumnTestScript.js'

export default {
    name: "Gen",
    components: { importTable ,initTable},
    data() {
        return {
            textarea: '',
            textArr :[],
            sql:"",
            //生成Sql弹框隐藏
            dialogVisible: false,
            // 遮罩层
            loading: true,
            // 唯一标识符
            uniqueId: "",
            // 选中数组
            ids: [],
            // 选中表数组
            tableNames: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表数据
            tableList: [],
            // 日期范围
            dateRange: "",
            tabPaneFilterOptionList: [
                {
                    dictValue: '1',
                    dictLabel: '选项1'
                },
                {
                    dictValue: '2',
                    dictLabel: '选项2'
                },
            ],
            // 查询参数
            queryParamsTabPaneFilterValue: "1",
            // 查询参数
            queryParams: {
                autumnParams: {},
                pageNum: 1,
                pageSize: 10,
                tableName: undefined,
                tableComment: undefined
            },
            // 预览参数
            preview: {
                currentRow:{},
                loading: true,

                open: false,
                title: "代码预览",
                data: {},
                activeName: "domain.java"
            },

            groupPreview:{
                loading: true,
                data: {},
                activeName: ""
            },
        };
    },
    created() {
        this.getList();
        this.mergeFromObject(this,autumnTestScript)
    },
    activated() {
        const time = this.$route.query.t;
        if (time != null && time != this.uniqueId) {
            this.uniqueId = time;
            // this.resetQuery();
        }
    },
    methods: {
        mapKeys(obj){
         return Object.keys(obj)[0]
        },
        //生成Sql语句的方法

        //转换
        handleSqlToInitTableInfo(){
            this.sql = ""
            let text = this.textarea.replace(/`/g, "")
            text=text.replace("\r","")
            this.textArr = text.split(/[\n]/)
            for(let i = 0;i<this.textArr.length;i++){
                this.sql +='column("'+ this.textArr[i]+'"),'+'\n'
            }
            // this.textarea = ""
        },
        close(){
            this.dialogVisible = false
            this.sql = ""

        },
        initTableBuild(){
            this.$refs.initTable.show()

        },
        /** 查询表集合 */
        getList() {
            this.loading = true;
            this.queryParams.sksJpaParams=this.queryParams.autumnParams
            listTable(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
                    this.tableList = response.data.list;
                    this.total = response.data.total;
                    this.loading = false;
                }
            );
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 生成代码操作 */
        handleGenTable(row) {
            const tableNames = row.tableName || this.tableNames;
            if (tableNames == "") {
                this.msgError("请选择要生成的数据");
                return;
            }
            if(row.genType === "1") {
                genCode(row.tableName).then(response => {
                    this.msgSuccess("成功生成到自定义路径：" + row.genPath);
                });
            } else {
                downLoadZip("/tool/gen/batchGenCode?tables=" + tableNames, "ruoyi");
            }
        },
        /** 同步数据库操作 */
        handleSynchDb(row) {
            const tableName = row.tableName;
            this.$confirm('确认要强制同步"' + tableName + '"表结构吗？', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function() {
                return synchDb(tableName);
            }).then(() => {
                this.msgSuccess("同步成功");
            })
        },
        /** 打开导入表弹窗 */
        openImportTable() {
            this.$refs.import.show();

        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = [];
            this.queryParams.autumnParams={}
            this.resetForm("queryForm");
            this.handleQuery();
        },
        handleChangeQueryParamsTabPane(){
            switch (Number(this.queryParamsTabPaneFilterValue)) {
                case 1:
                    this.loadPreviewTable()
                    break;
                case 2:
                    this.loadGroupPreviewTable()
                    break;
                default:
                    break;
            }

        },
        /** 预览按钮 */
        handlePreview(row) {
            this.queryParamsTabPaneFilterValue="1"
            this.preview.currentRow=row
            this.preview.open = true;
            this.handleChangeQueryParamsTabPane()
        },
        loadPreviewTable(){
            const row=this.preview.currentRow
            this.preview.data={}
            this.preview.loading=true
            previewTable(row.tableId).then(res => {
                this.preview.data = res.data;
                this.preview.loading=false
            });
        },
       loadGroupPreviewTable(){
           const row=this.preview.currentRow
           this.groupPreview.data={}
           this.groupPreview.loading=true
           groupPreviewTable(row.tableId).then(res=>{
               this.groupPreview.data = res.data;
               this.groupPreview.activeName=Object.keys(res.data)[0]||''
               this.groupPreview.loading=false
           })
       } ,
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.tableId);
            this.tableNames = selection.map(item => item.tableName);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 修改按钮操作 */
        handleEditTable(row) {
            const tableId = row.tableId || this.ids[0];
            this.$router.push("/gen/edit/" + tableId);
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const tableIds = row.tableId || this.ids;
            this.$confirm('是否确认删除表编号为"' + tableIds + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function() {
                return delTable(tableIds);
            }).then(() => {
                this.getList();
                this.msgSuccess("删除成功");
            })
        },
        handleClipboard(text, event) {
            clipboard(text, event)
            this.msgSuccess("已复制到剪贴板");
        }
    },
};
</script>
<style  scoped>
.btn {
    width: 100px;
    height: 50px;
    margin: 20px;
}
.sql11{
    width: 100%;
    /* background-color: rgb(209, 40, 40); */
    border: 1px solid #b9b9b9;
    line-height: 30px;
    padding: 30px;
    font-size: 16px;
}
</style>
